package de.gwtprime.server.servlets.cron;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import de.gwtprime.server.ChannelManager;
import de.gwtprime.server.model.Transaction;
import de.gwtprime.server.model.User2;
import de.gwtprime.server.model.wrapper.TransactionWrapper;
import de.gwtprime.server.util.RPCClient;
import de.gwtprime.shared.TransactionType;

/**
 * @author jan
 *
 */
public class ConfirmationServlet extends HttpServlet{

	/**
	 * Serial version ID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(ConfirmationServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		for(Transaction trans : Transaction.loadUnconfirmedTransactions()){

			synchronized (trans) {

				try {
					TransactionWrapper transWrapper = new TransactionWrapper(RPCClient.getInstance().getTransaction(trans.getTransactionId()));
					if(transWrapper.getConfirmations()>4){

						// If incoming transaction was found -> increase user balance
						if(trans.getType()==TransactionType.DEPOSIT){
							trans.setConfirmed(true);
							trans.persist();

							User2 u = trans.getUser();

							u.setBalanceBitcoin(u.getBalanceBitcoin()+trans.getAmount());
							u.persist();
							ChannelManager.pushToClient(u.getId().toString(), "newTransactionAvailable");
						}

					}
				} catch (Exception e) {
					logger.error("CRITICAL: confirming coins did fail", e);
				}
			}
		}
		
		resp.getWriter().println("confirmations checked");
	}
}
